import datetime

from django.db import models
# Create your models here.
#用户表，关系到发帖和评论表
from UserAPP.models import MS_USER


#写死的上传分类，因为不会用太多的地方
CATEGORY_TYPE = (
        (0, "通用"),
        (1, "安全"),
        (2, "学籍"),
        (3, "资助"),
    )


def upload_path_handler(instance,filename):  #这个函数功能是为了给UpLoadFile 上传定义文件目录用的
    print(CATEGORY_TYPE[instance.category_type][1])   #这个是 数组中选择对应的栏目，由于写死，废弃
    print(filename)
    print(123123123123)
    print(instance.category.name)   #对应的分类文件夹
    print(instance.category.parent_category.name)   #对应的分类文件夹
    now_time = datetime.datetime.now().strftime('%Y-%m')  #分类对应的一级分类
    return "{0}/{1}/{2}/{3}/{4}".format('上传资料库',instance.category.parent_category.name,instance.category.name, now_time, datetime.datetime.now().strftime('%Y%m%d%H%M%S')+'_'+filename)

class Tui(models.Model):
    """
    推荐，xxx推荐板块
    """
    id = models.AutoField(primary_key=True)
    name = models.CharField('文章形象标签', max_length=100,default='热门标签')

    class Meta:
        verbose_name = '文章标签'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name



    def get_category_tree(self):
        """
        递归获得分类目录的父级
        :return:
        """
        categorys = []

        def parse(category):
            categorys.append(category)
            if category.parent_category:
                parse(category.parent_category)


        return categorys



class Category(models.Model):
    """
        板块类别
        """
    CATEGORY_TYPE = (
        (0, "[一级板块]"),
        (1, "---[二级板块]"),
        (2, "------[三级板块]"),
    )
    id = models.AutoField(primary_key=True)
    name = models.CharField(default="热门推荐", max_length=30, verbose_name="板块名", help_text="板块名")
    code = models.CharField(default="0", max_length=30, verbose_name="板块code", help_text="板块code")
    desc = models.CharField(default="热门入手商品",max_length=200, verbose_name="板块描述", help_text="板块描述",null=True,blank=True)
    category_type = models.IntegerField(choices=CATEGORY_TYPE,default=0, verbose_name="板块级别", help_text="类目级别")
    parent_category = models.ForeignKey("self", null=True, blank=True, verbose_name="父类目级别", help_text="父目录",
                                        related_name="sub_cat",on_delete=models.CASCADE)
    is_tab = models.BooleanField(default=False, verbose_name="是否导航", help_text="是否导航")
    categoryWeight = models.IntegerField(default=0,null=False,help_text="前后顺序",verbose_name="同级顺序")

    class Meta:
        verbose_name = "文章板块设置"
        verbose_name_plural = verbose_name
        ordering = ['categoryWeight']

    def __str__(self):
        if self.category_type == 1:
            return f"id:{self.id}; {self.CATEGORY_TYPE[self.category_type][1]}--{self.name}"
        if self.category_type == 2:
            return f"id:{self.id} ;{self.CATEGORY_TYPE[self.category_type][1]}----{self.name}"
        return f"id:{self.id}; {self.CATEGORY_TYPE[self.category_type][1]}{self.name}"


    def getFiles(self):
        all_files = UpLoadFile.objects.filter(category=self)[:10]
        return all_files



    def get_sub_categorys(self):
        """
        获得所需要的子类对象
        获得当前分类目录所有子集,意思是可以在view中调用这个方法，获得某个类目下的所有子集
        :return:
        """
        categorys = []
        all_categorys = Category.objects.all()
        def parse(category):
            # if category not in categorys:
            #     categorys.append(category)
            childs = all_categorys.filter(parent_category=category)
            for child in childs:
                if category not in categorys:
                    categorys.append(child)
                parse(child)

        parse(self)
        return categorys



class UpLoadFile(models.Model):
    """
    推荐，上传内容记录
    """

    id = models.AutoField(primary_key=True)
    fileName = models.CharField('文件名', max_length=100,default='热门标签',null=False,blank=False)
    file = models.FileField(upload_to=upload_path_handler, default='abc/2.jpg', verbose_name="文件名称", blank=True, null=True)
    category_type = models.IntegerField(choices=CATEGORY_TYPE,default=0, verbose_name="存储类目", help_text="类目级别")
    date = models.DateTimeField(auto_now_add=True)  # 操作上传更新时间
    category = models.ForeignKey(Category, verbose_name='递归分类', null=True, blank=True,
                                 on_delete=models.SET_NULL)


    class Meta:
        verbose_name = '文件内容'
        verbose_name_plural = verbose_name
        ordering = ['-date']
    def __str__(self):
        return self.fileName


def get_MS_USER_FK():
    return MS_USER.objects.get_or_create(id=0)[0].id
def get_Tui_FK():
    return Tui.objects.get_or_create(id=0)[0].id
def get_Category_FK():
    return Category.objects.get_or_create(id=0)[0].id
#帖子内容表
class DetailPage(models.Model):
    tui = models.ForeignKey('Tui',default=1,null=True, on_delete=models.SET_DEFAULT)
    pageid = models.AutoField(primary_key=True)
    tbid = models.IntegerField(default=0, blank=False, null=False)  # 淘宝的商品id
    detail_auther = models.ForeignKey('UserAPP.MS_USER',default=get_MS_USER_FK,null=True, on_delete=models.SET_DEFAULT)
    title = models.CharField(max_length=50,blank=False,null=False)
    content = models.TextField(max_length=15000,blank=False,null=False)
    category = models.ForeignKey(Category, verbose_name='递归分类', null=True, blank=True,
                                 on_delete=models.SET_NULL)
    tags = models.CharField(max_length=50,blank=True,null=True)
    POSTtime = models.DateTimeField(auto_now_add=True)  # 操作更新时间
    date = models.DateTimeField(blank=True, null=True, default=None, verbose_name='发帖时间，可修改')
    readNum =models.IntegerField(default=0,blank=False,null=True)

    def __str__(self):
        return f'发帖id：{self.pageid},发帖人{self.detail_auther.nickName}'
    class Meta:
        verbose_name = '文章'
        verbose_name_plural = verbose_name
        ordering = ['-POSTtime']

#评论表
class Comment(models.Model):
    id =models.AutoField(primary_key=True)
    comment_auther = models.ForeignKey('UserAPP.MS_USER',default=get_MS_USER_FK, on_delete=models.CASCADE)
    comment_detailpage = models.ForeignKey('DetailPage', on_delete=models.CASCADE)
    comment_content = models.TextField(max_length=1000,blank=False,null=False)
    date = models.DateTimeField(auto_now_add=True)  # 操作更新时间
    likeNum = models.IntegerField(default=0,blank=False,null=True)
    def __str__(self):
        return f'评论人：{self.comment_auther.nickName},评论的帖子：{self.comment_detailpage.title}'
    class Meta:
        verbose_name = '文章评论'
        verbose_name_plural = verbose_name
        ordering = ['-date']


# JD程序发帖记录，记录每次发帖的内容，是否已发过，如若表里边存在就是已经发过了
class JDItemId(models.Model):
    id = models.AutoField(primary_key=True)
    jDid = models.CharField(max_length=30,blank=False,null=False)

    def __str__(self):
        return f'{self.jDid}'

    class Meta:
        verbose_name = '京东搜索过ID记录'
        verbose_name_plural = verbose_name
        ordering = ['id']


# 随机返回假的用户名和头像
class RandomUserInfo(models.Model):
    id = models.AutoField(verbose_name='随机用户',primary_key=True)# 随机产生用户信息，名字和头像
    userName = models.CharField(verbose_name='昵称',max_length=300, default='',blank=False,null=False) #禁止空
    # ImageField 就是把图片保存在这个路径中，具体的复制到路径并不是由数据库model来处理的，是上传form时候根据保存的图片路径决定的
    # 在view中如何保存保存图片路径呢，
    user_img = models.ImageField(upload_to='userHEAD/', default='userHEAD/2.jpg', blank=True, null=True) #允许空


    class Meta:
        verbose_name = '(通用API)随机返回假的用户名和头像'
        verbose_name_plural = verbose_name
        ordering = ['id']